package main

import (
	"encoding/json"
	"fmt"
	"net"

	"gitee.com/yutiandou/wdRPC/server/config"
	"gitee.com/yutiandou/wdRPC/server/connpool"
	"gitee.com/yutiandou/wdRPC/server/worker"

	"gitee.com/yutiandou/wdtools/wdlog"

	"gitee.com/yutiandou/wdRPC/common/connect"
	"gitee.com/yutiandou/wdRPC/common/routing"
)

func RegistServer() {
	conn, err := net.Dial("tcp", config.Conf.LUAddress)
	if wdlog.PanicErr(err) {
		return
	}
	node := &routing.Node{
		NodeName: config.Conf.ServerName,
		Address:  config.Conf.Address,
		Weight:   config.Conf.Weight,
		Stat:     true,
	}
	info, err := json.Marshal(node)
	if wdlog.PanicErr(err) {
		return
	}
	quit := make(chan uint32, 100)
	worker := connect.NewNetNode(1, conn, quit)
	handle := make(map[uint32]connect.ConnPoolHand)
	handle[1] = func(n *connect.NetNode, data []byte) {
		var requ = &connect.Warn{}
		err = json.Unmarshal(data, requ)
		fmt.Println(requ)
		fmt.Println(string(data))
	}
	go worker.Read(handle)
	worker.Write(1, info)
}

func Start() {
	conn, err := net.Listen("tcp", config.Conf.Address)
	if wdlog.PanicErr(err) {
		return
	}
	worker := worker.NewWorkers(call)
	defer worker.OffDuty()
	cpool := connpool.NewCltPool(worker.BlockPipe, worker.MsgQueue)
	for {
		newconn, err := conn.Accept()
		if wdlog.Error(err) {
			continue
		}
		cpool.AddNode(newconn)
	}

}

var call = func(*connpool.Msg) {}

func SetHandler(f func(*connpool.Msg)) {
	call = f
}

func main1() {
	RegistServer()
	SetHandler(func(msg *connpool.Msg) {
		fmt.Println(string(msg.Data))
		msg.Node.Write(msg.Data)
	})
	Start()
}
